package com.xlh.util;

import cn.hutool.core.lang.Console;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author zhr 2019/12/20
 * <p>wkwtmltopdf转pdf的工具类与工具方法</p>
 */
public class WkhtmltopdfUtil {

    private static Logger logger = LoggerFactory.getLogger(WkhtmltopdfUtil.class);

    private static final String CMD = "wkhtmltopdf %s %s";

    public static boolean html2pdf(String htmlPath, String pdfPath) {

        // 拼接命令
        String cmd = String.format(CMD, htmlPath, pdfPath);

        try {
            Console.log(cmd);
            // 执行文档转换命令
            Process process = Runtime.getRuntime().exec(cmd);

            // 解析并处理命令结果
            BufferedInputStream bis = new BufferedInputStream(process.getInputStream());

            BufferedReader br = new BufferedReader(new InputStreamReader(bis));
            StringBuffer buffer = new StringBuffer();
            String line;

            while ((line = br.readLine()) != null) {
                buffer.append(line).append("\n");
            }

            logger.info(buffer.toString());

            bis.close();
            br.close();

            // 解析并处理命令结果(只收集错误信息)
            process.waitFor();
            if (process.exitValue() != 0) {
                bis = new BufferedInputStream(process.getErrorStream());
                br = new BufferedReader(new InputStreamReader(bis));

                buffer = new StringBuffer();
                while ((line = br.readLine()) != null) {
                    buffer.append(line);
                }
                throw new IOException(buffer.toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }

        return true;
    }

//    public static void main(String[] args) {
//        String htmlPath = "F:\\temp/e4ad62cc46934cf38ce5392a8beb1d76.html";
//        String pdfPath = "c:\\Users\\962213579\\Desktop\\1.pdf";
//        html2pdf(htmlPath, pdfPath);
//    }

//    public static void main(String[] args) {
//        String words = "> ajknalksdalskdqiwlandaklsd > aklsnkdaklsjdalskdjoiqwndasldas";
//        if (Objects.equals'(>', words.charAt(0))){
//            System.out.println("首位引用");
//            words = words.substring(2);
//            System.out.println(words);
//        }
//    }
}
